// 与用户模块相关的中间件
const { NAME_AND_PASSWORD_IS_REQUIRED, USER_DOES_NOT_EXIST, USER_ALREADY_EXISTS, INCORRENCT_PASSWORD } = require('../error/errorType')
const userService = require('../service/user.service')
// 处理登录的中间件
const verifyLogin = async (ctx, next) => {
  //参数缺少
  const { name, password } = ctx.request.body
  if (!name || !password) {
    return ctx.app.emit('error', new Error(NAME_AND_PASSWORD_IS_REQUIRED), ctx)
  }
  //判断有没有user存在用户
  const result = await userService.getUserInfoByName(name)
  let [userInfo] = result
  if (!userInfo) {
    return ctx.app.emit('error', new Error(USER_DOES_NOT_EXIST), ctx)
  }
  //密码不正确
  if (userInfo.password != password) {
    return ctx.app.emit('error', new Error(INCORRENCT_PASSWORD), ctx)
  }
  ctx.userInfo = userInfo
  await next()

}


// 处理注册的中间件
const verifyRegister = async (ctx, next) => {
  //参数缺少
  const { name, password } = ctx.request.body
  if (!name || !password) {
    return ctx.app.emit('error', new Error(NAME_AND_PASSWORD_IS_REQUIRED), ctx)
  }

  //判断有没有user存在用户
  const result = await userService.getUserInfoByName(name)
  console.log(result.length);
  if (result.length > 0) {
    return ctx.app.emit('error', new Error(USER_ALREADY_EXISTS), ctx)
  }
  await next()
}

// ...

module.exports = {
  verifyLogin,
  verifyRegister
}